package com.ecommerce.service;

import com.ecommerce.entity.Category;
import com.ecommerce.entity.Product;
import com.ecommerce.entity.ProductImage;
import com.ecommerce.entity.Order;
import com.ecommerce.entity.OrderItem;
import com.ecommerce.repository.CategoryRepository;
import com.ecommerce.repository.ProductRepository;
import com.ecommerce.repository.ProductImageRepository;
import com.ecommerce.repository.BannerRepository;
import com.ecommerce.repository.OrderRepository;
import com.ecommerce.repository.OrderItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import com.ecommerce.entity.Banner;

@Service
public class DataInitializationService implements CommandLineRunner {

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ProductRepository productRepository;
    
    @Autowired
    private ProductImageRepository productImageRepository;
    
    @Autowired
    private BannerRepository bannerRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("开始数据初始化...");
        
        // 强制重新创建分类
        System.out.println("当前分类数量: " + categoryRepository.count());
        initializeCategories();
        
        // 强制重新创建商品
        System.out.println("当前商品数量: " + productRepository.count());
        initializeProducts();
        
        // 强制重新创建商品图片
        System.out.println("当前商品图片数量: " + productImageRepository.count());
        initializeAllProductImages();
        
        // 强制重新创建轮播图
        System.out.println("当前轮播图数量: " + bannerRepository.count());
        initializeBanners();
        
        // 初始化测试订单数据
        System.out.println("当前订单数量: " + orderRepository.count());
        initializeTestOrders();
        
        System.out.println("数据初始化完成！");
        System.out.println("分类数量: " + categoryRepository.count());
        System.out.println("商品数量: " + productRepository.count());
        System.out.println("商品图片数量: " + productImageRepository.count());
        System.out.println("轮播图数量: " + bannerRepository.count());
        System.out.println("订单数量: " + orderRepository.count());
    }

    private void initializeCategories() {
        List<Category> categories = Arrays.asList(
            createCategory("手机数码", "智能手机、平板电脑等数码产品"),
            createCategory("服装鞋包", "男装、女装、鞋靴、箱包等"),
            createCategory("家居用品", "家具、家纺、厨具等家居用品"),
            createCategory("美妆护肤", "化妆品、护肤品、香水等"),
            createCategory("运动户外", "运动服装、运动器材、户外用品"),
            createCategory("图书音像", "图书、音像制品、电子书等"),
            createCategory("食品生鲜", "零食、饮料、生鲜食品等"),
            createCategory("母婴用品", "婴儿用品、儿童玩具、孕妇用品等")
        );
        
        categoryRepository.saveAll(categories);
        System.out.println("分类数据初始化完成");
    }

    private void initializeProducts() {
        System.out.println("开始初始化商品数据...");
        
        try {
            // 获取第一个分类作为默认分类
            List<Category> allCategories = categoryRepository.findAll();
            System.out.println("数据库中所有分类: " + allCategories.stream().map(Category::getName).toList());
            
            if (allCategories.isEmpty()) {
                System.out.println("没有找到分类，创建默认分类...");
                Category defaultCategory = createCategory("默认分类", "默认商品分类");
                defaultCategory = categoryRepository.save(defaultCategory);
                allCategories.add(defaultCategory);
            }
            
            Category defaultCategory = allCategories.get(0);
            System.out.println("使用分类: " + defaultCategory.getName());
            
            // 创建测试商品
            List<Product> testProducts = Arrays.asList(
                createProduct("iPhone 15 Pro", "最新款iPhone，搭载A17 Pro芯片，支持5G网络", 
                    new BigDecimal("7999.00"), new BigDecimal("8999.00"), 100, "IPHONE15PRO", defaultCategory, "Apple", "iPhone 15 Pro", 1500, 50),
                createProduct("MacBook Pro", "专业级笔记本电脑，适合开发者和设计师", 
                    new BigDecimal("12999.00"), new BigDecimal("13999.00"), 50, "MACBOOKPRO", defaultCategory, "Apple", "MacBook Pro", 800, 20),
                createProduct("AirPods Pro", "无线降噪耳机，支持主动降噪", 
                    new BigDecimal("1999.00"), new BigDecimal("2299.00"), 200, "AIRPODSPRO", defaultCategory, "Apple", "AirPods Pro", 1200, 80),
                createProduct("iPad Air", "轻薄平板电脑，适合工作和娱乐", 
                    new BigDecimal("4799.00"), new BigDecimal("5299.00"), 80, "IPADAIR", defaultCategory, "Apple", "iPad Air", 600, 30),
                createProduct("Apple Watch", "智能手表，健康监测和运动追踪", 
                    new BigDecimal("2999.00"), new BigDecimal("3299.00"), 120, "APPLEWATCH", defaultCategory, "Apple", "Apple Watch", 900, 40),
                createProduct("Nike Air Max", "经典运动鞋，舒适透气", 
                    new BigDecimal("899.00"), new BigDecimal("999.00"), 200, "NIKEAIRMAX", defaultCategory, "Nike", "Air Max", 500, 100),
                createProduct("Adidas Ultraboost", "专业跑步鞋，能量回弹", 
                    new BigDecimal("1299.00"), new BigDecimal("1499.00"), 150, "ADIDASULTRABOOST", defaultCategory, "Adidas", "Ultraboost", 600, 80),
                createProduct("IKEA 书桌", "简约设计，实用耐用", 
                    new BigDecimal("599.00"), new BigDecimal("699.00"), 80, "IKEADESK", defaultCategory, "IKEA", "书桌", 800, 30),
                createProduct("SK-II 神仙水", "明星产品，改善肤质", 
                    new BigDecimal("1299.00"), new BigDecimal("1499.00"), 100, "SKIILOTION", defaultCategory, "SK-II", "神仙水", 200, 80),
                createProduct("《三体》全集", "刘慈欣科幻小说，三册精装", 
                    new BigDecimal("99.00"), new BigDecimal("129.00"), 200, "THREEBODYBOOK", defaultCategory, "重庆出版社", "三体全集", 1000, 150)
            );
            
            productRepository.saveAll(testProducts);
            System.out.println("商品创建成功，数量: " + testProducts.size());
            
        } catch (Exception e) {
            System.err.println("商品数据初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void initializeAllProductImages() {
        List<Product> products = productRepository.findAll();
        
        // 在线图片URL列表
        String[] onlineImages = {
            "https://picsum.photos/400/400?random=1",
            "https://picsum.photos/400/400?random=2", 
            "https://picsum.photos/400/400?random=3",
            "https://picsum.photos/400/400?random=4",
            "https://picsum.photos/400/400?random=5",
            "https://picsum.photos/400/400?random=6",
            "https://picsum.photos/400/400?random=7",
            "https://picsum.photos/400/400?random=8",
            "https://picsum.photos/400/400?random=9",
            "https://picsum.photos/400/400?random=10"
        };
        
        for (Product product : products) {
            // 为每个商品创建3-5张图片
            int imageCount = 3 + (int)(Math.random() * 3); // 3-5张图片
            
            for (int i = 0; i < imageCount; i++) {
                ProductImage image = new ProductImage();
                image.setProduct(product);
                
                // 使用在线图片URL
                int imageIndex = (product.getId().intValue() + i) % onlineImages.length;
                image.setImageUrl(onlineImages[imageIndex]);
                
                image.setImageName(product.getName() + " - 图片" + (i + 1));
                image.setAltText(product.getName() + " 产品图片");
                image.setSortOrder(i);
                image.setIsMain(i == 0); // 第一张图片为主图
                image.setIsActive(true);
                
                productImageRepository.save(image);
            }
        }
        System.out.println("商品图片数据初始化完成");
    }

    private Category createCategory(String name, String description) {
        Category category = new Category();
        category.setName(name);
        category.setDescription(description);
        // 移除不存在的setImageUrl调用
        return category;
    }

    private Product createProduct(String name, String description, BigDecimal price, BigDecimal originalPrice, 
                                Integer stock, String sku, Category category, String brand, String model, 
                                Integer viewCount, Integer soldCount) {
        Product product = new Product();
        product.setName(name);
        product.setDescription(description);
        product.setPrice(price);
        product.setOriginalPrice(originalPrice);
        product.setStock(stock);
        product.setSku(sku);
        product.setCategory(category);
        product.setBrand(brand);
        product.setModel(model);
        product.setWeightKg(new BigDecimal("0.5"));
        product.setDimensions("10x10x5cm");
        product.setViewCount(viewCount);
        product.setSoldCount(soldCount);
        
        // 使用在线图片URL作为主图
        String[] mainImages = {
            "https://picsum.photos/400/400?random=11",
            "https://picsum.photos/400/400?random=12",
            "https://picsum.photos/400/400?random=13",
            "https://picsum.photos/400/400?random=14",
            "https://picsum.photos/400/400?random=15",
            "https://picsum.photos/400/400?random=16",
            "https://picsum.photos/400/400?random=17",
            "https://picsum.photos/400/400?random=18",
            "https://picsum.photos/400/400?random=19",
            "https://picsum.photos/400/400?random=20"
        };
        
        int imageIndex = (int)(Math.random() * mainImages.length);
        product.setMainImage(mainImages[imageIndex]);
        
        return product;
    }
    
    private void initializeBanners() {
        System.out.println("开始初始化轮播图数据...");
        
        // 在线轮播图URL列表
        String[] bannerImages = {
            "https://picsum.photos/800/400?random=21",
            "https://picsum.photos/800/400?random=22",
            "https://picsum.photos/800/400?random=23",
            "https://picsum.photos/800/400?random=24",
            "https://picsum.photos/800/400?random=25"
        };
        
        String[] bannerTitles = {
            "新品上市",
            "限时特惠",
            "品牌推荐",
            "热销商品",
            "会员专享"
        };
        
        String[] bannerDescriptions = {
            "最新商品，品质保证",
            "限时优惠，抢购从速",
            "精选品牌，值得信赖",
            "热销商品，好评如潮",
            "会员专享，更多优惠"
        };
        
        // 创建轮播图数据
        for (int i = 0; i < bannerImages.length; i++) {
            Banner banner = new Banner();
            banner.setTitle(bannerTitles[i]);
            banner.setImageUrl(bannerImages[i]);
            banner.setDescription(bannerDescriptions[i]);
            banner.setLink("/category"); // 默认跳转到分类页
            banner.setSortOrder(i);
            banner.setIsActive(true);
            banner.setIsMain(i == 0); // 第一张为主图
            
            bannerRepository.save(banner);
        }
        
        System.out.println("轮播图数据初始化完成");
    }

    private void initializeTestOrders() {
        System.out.println("开始初始化测试订单数据...");
        
        try {
            // 创建测试订单
            Order testOrder1 = new Order();
            testOrder1.setUserId(1L);
            testOrder1.setOrderNumber("ORDER202412011200001");
            testOrder1.setStatus(Order.OrderStatus.PENDING);
            testOrder1.setTotalAmount(new BigDecimal("7999.00"));
            testOrder1.setReceiverName("张三");
            testOrder1.setReceiverPhone("13800138001");
            testOrder1.setReceiverAddress("北京市朝阳区某某街道某某小区1号楼101室");
            testOrder1.setPaymentMethod(Order.PaymentMethod.ALIPAY);
            testOrder1.setPaymentStatus(Order.PaymentStatus.UNPAID);
            testOrder1.setRemark("请尽快发货");
            
            Order savedOrder1 = orderRepository.save(testOrder1);
            
            // 创建订单商品
            OrderItem orderItem1 = new OrderItem();
            orderItem1.setOrder(savedOrder1);
            orderItem1.setProductId(1L);
            orderItem1.setProductName("iPhone 15 Pro");
            orderItem1.setProductImage("https://picsum.photos/400/400?random=1");
            orderItem1.setPrice(new BigDecimal("7999.00"));
            orderItem1.setQuantity(1);
            orderItem1.setSubtotal(new BigDecimal("7999.00"));
            
            orderItemRepository.save(orderItem1);
            
            // 创建第二个测试订单
            Order testOrder2 = new Order();
            testOrder2.setUserId(1L);
            testOrder2.setOrderNumber("ORDER202412011200002");
            testOrder2.setStatus(Order.OrderStatus.PAID);
            testOrder2.setTotalAmount(new BigDecimal("12999.00"));
            testOrder2.setReceiverName("李四");
            testOrder2.setReceiverPhone("13800138002");
            testOrder2.setReceiverAddress("上海市浦东新区某某路某某大厦A座1001室");
            testOrder2.setPaymentMethod(Order.PaymentMethod.WECHAT);
            testOrder2.setPaymentStatus(Order.PaymentStatus.PAID);
            testOrder2.setRemark("请包装精美一些");
            
            Order savedOrder2 = orderRepository.save(testOrder2);
            
            // 创建订单商品
            OrderItem orderItem2 = new OrderItem();
            orderItem2.setOrder(savedOrder2);
            orderItem2.setProductId(2L);
            orderItem2.setProductName("MacBook Pro");
            orderItem2.setProductImage("https://picsum.photos/400/400?random=2");
            orderItem2.setPrice(new BigDecimal("12999.00"));
            orderItem2.setQuantity(1);
            orderItem2.setSubtotal(new BigDecimal("12999.00"));
            
            orderItemRepository.save(orderItem2);
            
            System.out.println("测试订单数据初始化完成");
            
        } catch (Exception e) {
            System.err.println("测试订单数据初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 